<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/2/19 0019
 * Time: 22:45
 */
$server = new Swoole\Server('0.0.0.0', 9501, SWOOLE_PROCESS, SWOOLE_SOCK_TCP);

$server->set([
    'worker_num' => 1,
    'heartbeat_idle_time' => 600,
    'heartbeat_check_interval' => 60
]);
$server->on('connect', function ($serv, $fd) {
    echo "有新的客户端连接，连接标识为$fd" . PHP_EOL;
});

$server->on('receive', function ($serv, $fd, $from_id, $data) {

    $client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);

//注册连接成功回调
    $client->on("connect", function ($cli) use ($data) {
        $cli->send($data + 1);
    });

//注册数据接收回调
    $client->on("receive", function ($cli, $data) use ($serv, $fd) {
        $serv->send($fd, $data + 1);
//        echo "Received: " . $data . "\n";
    });

//注册连接失败回调
    $client->on("error", function ($cli) {
        echo "Connect failed\n";
    });

//注册连接关闭回调
    $client->on("close", function ($cli) {
        echo "Connection close\n";
    });

//发起连接
    $client->connect('127.0.0.1', 9502, 0.5);

});

$server->on('close', function ($serv, $fd) {
    echo "编号为{$fd}的客户端已经关闭." . PHP_EOL;
});


$server->start();